from django.shortcuts import render
from rest_framework.views import APIView
from rest_framework.response import Response
from django.contrib.auth.hashers import check_password,make_password
from .models import User
from django.utils import timezone
import jwt,redis,random,json,time
from mall_admin import settings
from rest_framework_jwt.utils import jwt_encode_handler
# from .utils import send_sms_code
from celery_tasks.sms_code.tasks import send_sms_code

# Create your views here.
def gen_jwt_token(user):
    obj={
        'user':user.username
    }
    token=jwt.encode(payload=obj,key=settings.SECRET_KEY,algorithm='HS256')
    return token
class Login(APIView):
    def post(self,request):
        # 1.获取前端数据
        username=request.data.get('username')
        pwd=request.data.get('pwd')
        mobile=request.data.get('mobile')
        sms_code=request.data.get('sms_code')
        r=redis.Redis(host='localhost',port=6379,db=7)
        tcode=r.get(f'sms_{mobile}')
        # if tcode.decode()!=sms_code:
        #     return Response({'code':404,'msg':'验证码错误'})
        # 2.判断用户是否存在
        try:
            user= User.objects.get(username=username)
        except Exception as e:
            print(e)
            #如果不存在，创建用户
            try:
                user=User.objects.create(username=username,phone=mobile,password=make_password(pwd))
            except Exception as e:
                print(e)
                return Response({'code':204,'msg':'用户注册失败'})
            # 生成jwt token
            payload={
                'user':user.username
            }
            token=jwt_encode_handler(payload)
            # print('.....>>>>>>>>>>'+token)
            return Response({'code':200,'msg':'注册并登录成功','user':user.username,'token':token})
        # 生成 jwt token
        token=gen_jwt_token(user)
        # 如果存在，校验密码
        if check_password(pwd,user.password):
            # 更新最后登录时间
            user.last_login=timezone.now()
            user.save()
            # 密码正确，登陆成功
            return Response({'code':200,'msg':'登录成功','user':user.username,'token':token})
        else:
            # 密码错误，登录失败
            return Response({'code':403,'msg':'密码错误'})
class SmSCode(APIView):
    def get(self,request):
        """发送短信验证码"""
        # 接收前端手机号
        mobile=request.query_params.get('mobile')
        print('手机号>>>>>'+ mobile)
        # 生成短信验证码
        data=random.randint(000000,999999)
        if mobile:
            resp=send_sms_code.delay(mobile,data)
            if resp:
                r=redis.Redis(host='localhost',port=6379,db=7)
                r.set(f'sms_{mobile}',data,ex=600)
                r.close()
                return Response({'code':200,'msg':'验证码发送成功'})
            else:
                return Response({'code':500,'msg':'验证码发送失败'})
class DailyUser(APIView):
    def get(self,request):
        """统计日活跃用户"""
        date=time.strftime('%y-%m-%d')
        print('今天是》》》',date)
        user_count=User.objects.filter(last_login__contains=date).count()
        return Response({'code':200,'msg':'统计日活成功','total_count':user_count})
class DayIncrement(APIView):
    def get(self,request):
        """日增用户"""
        date = time.strftime('%y-%m-%d')
        print('今天是》》》', date)
        user_count = User.objects.filter(created_time__contains=date).count()
        return Response({'code': 200, 'msg': '统计日增成功', 'total_count': user_count})
class UsersCount(APIView):
    def get(self,request):
        """统计用户数量"""
        users=User.objects.all().count()
        return Response({'code':200,'msg':'统计所有用户成功','total_count':users})
from django.db.models import Count
from django.db import connection
from django.http.response import JsonResponse
class MouthIncrementUser(APIView):
    def get(self,request):
        """获取当月明天新增用户数"""
        # 获取当前月
        year_mouth=time.strftime('%y-%m',time.localtime(time.time()))
        # 默认使用数据库链接
        # date_trunc_sql:执行sql语句
        select={'day':connection.ops.date_trunc_sql('day','created_time')}
        # extra ：运行sql
        # annotate : 聚合函数，会根据传入 的参数进行统计：根据传入的id进行统计
        data=User.objects.filter(created_time__contains=year_mouth).extra(select=select).values('day').annotate(number=Count(id))
        data_list=[]
        for i in data:
            data_list.append({
                'count':i['number'],
                'date':i['day']
            })
        return JsonResponse(data_list,safe=False)

class MouthLivejmUser(APIView):
    def get(self,request):
        """获取当月明天活跃用户数"""
        # 获取当前月
        year_mouth=time.strftime('%y-%m',time.localtime(time.time()))
        # 默认使用数据库链接
        # date_trunc_sql:执行sql语句
        select={'day':connection.ops.date_trunc_sql('day','last_login')}
        # extra ：运行sql
        # annotate : 聚合函数，会根据传入 的参数进行统计：根据传入的id进行统计
        data=User.objects.filter(created_time__contains=year_mouth).extra(select=select).values('day').annotate(number=Count(id))
        data_list=[]
        for i in data:
            data_list.append({
                'count':i['number'],
                'category':i['day']
            })
        return JsonResponse(data_list,safe=False)
class GetUser(APIView):
    def get(self, request):
        pagesize=int(request.query_params.get('pagesize'))
        currentpage=int(request.query_params.get('currentPage'))
        print(type(pagesize),type(currentpage))
        user_data = User.objects.all()[(currentpage-1)*pagesize:(currentpage*pagesize)]
        #     将数据进行序列化：
        user_list=[]
        for i in user_data:
            user_list.append({
                'id':i.id,
                'username':i.username,
                'phone':i.phone,
                'email':i.email,
                'password':i.password
            })
        return Response({
            'data':user_list,
            'total':User.objects.all().count()
        })
    def post(self,request):
        key=request.data.get('key')
        print(type(key))
        from django.db.models import Q
        user=User.objects.filter(Q(username=key)|Q(email=key)|Q(phone=key))
        print(user)
        if not user:
            return Response({'code':400,'msg':'数据不存在'})
        user_list=[]
        for i in user:
            user_list.append({
                'id': i.id,
                'username': i.username,
                'phone': i.phone,
                'email': i.email
            })
        return Response(user_list)

class AddUser(APIView):
    def post(self, request):
        #         获取前端传递的数据：
        username = request.data.get('username')
        password = request.data.get('password')
        phone = request.data.get('mobile')
        email = request.data.get('email')
        # if not all([username,password,phone,email]):
        #     return Response({'msg':'数据不齐全！','code':404})
        try:
            User.objects.get(username=username)
            return Response({'msg': '用户已存在！', 'code': 404})
        except Exception as e:
            print(e)
            #         添加数据：
            User.objects.create(
                username=username,
                password=make_password(password),
                phone=phone,
                email=email,
            )
        return Response({'msg': '添加成功', 'code': 200})

class UserInfo(APIView):
    def delete(self,request,id):
# #         删除数据：
# #         找到对应的数据
        try:
            User.objects.get(id=id).delete()
        except Exception as e:
            print(e)
            return Response({'msg':'数据不存在！','code':404})
        return Response({'msg':'删除成功','code':200})
    def put(self,request,id):
#         获取前端传递的数据：
        username = request.data.get('username')
        password = request.data.get('password')
        phone = request.data.get('phone')
        email = request.data.get('email')
        print(username)
        print(password)
        try:
            #         循环添加：
            user = User.objects.get(id=id)
            print(user.phone)
            #         进行修改：
            pwd = make_password(password)
            user.username = username
            user.phone = phone
            user.email = email
            user.password = pwd
            user.save()
            return Response({'msg': '更新成功', 'code': 200})
        #     如果有，添加到数据库中：
        except Exception as e:
            print(e)
            return Response({'msg':'数据不存在！','code':404})


    def get(self, request, id):
        #     获取指定id数据：
        try:
            user_data = User.objects.get(id=id)
        except Exception as e:
            print(e)
            return Response({'msg': '数据不存在！', 'code': 404})
        #     将数据进行序列化：
        user_list = {
            'id': user_data.id,
            'username': user_data.username,
            'phone': user_data.phone,
            'email': user_data.email,
            'password': user_data.password,
        }
        print(user_list)
        return Response(user_list)
